package com.kitty.web.common;

import com.kitty.common.utils.AndroidDesUtil;
import com.kitty.game.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 通用请求处理
 * 
 * @author wanfeng
 */
@Controller
@RequestMapping
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload2")
    @ResponseBody
    public AjaxResult uploadFile2(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = FileUploadUtils.defaultBaseDir;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload2(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通用下载
     */
    @GetMapping("down")
    public void fileDownload(HttpServletResponse response, HttpServletRequest request)
    {
        boolean mobileDevice = AndroidDesUtil.isMobileDevice(request.getHeader("User-Agent"));
        if(mobileDevice){
            try
            {
                String realFileName = "atmu_2.083r.0208_2.083r.0208.2.zip";
                String file = "C:/hotupdate/"+realFileName;
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-dFileUtilsata");
                response.setHeader("Content-Disposition","attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
                FileUtils.writeBytes(file, response.getOutputStream());
            }
            catch (Exception e)
            {
                log.error("下载文件失败", e);
            }
        }
    }


}
